using System;
using System.Reflection;
using EPiServer.Core;

namespace EPiSugar.EntityAdapter.PropertyBinders
{
    public class PropertyBinder : IPropertyBinder
    {
        public static readonly object[] NoParameters = new object[0];
        public string SourceProperty { get; set; }
        public PropertyInfo DestinationProperty { get; set; }


        public PropertyBinder(string sourceProperty, PropertyInfo destinationProperty)
        {
            SourceProperty = sourceProperty;
            DestinationProperty = destinationProperty;
        }


        protected virtual void SetValue(object instance, object value)
        {
            if (value != null && DestinationProperty.PropertyType != value.GetType())
                value = Convert.ChangeType(value, DestinationProperty.PropertyType);
            DestinationProperty.SetValue(instance, value, NoParameters);
        }

        public virtual void Bind(PageData sourcePage, object toInstance)
        {
            object value = sourcePage[SourceProperty];
            if (value != null)
            {
                SetValue(toInstance, value);
            }
        }

        public override string ToString()
        {
            return SourceProperty + "->" + DestinationProperty.Name;
        }
    }
}